# Get all projects
# API: https://build.tarsier-infra.com/build
from bs4 import BeautifulSoup
import os, sys

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + '../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'riscv_build_dataset.settings')
import django

django.setup()

import requests
from config import BASE_URL
from obs.models import obs_project


def get_projects():
    url = f'{BASE_URL}/build'

    # It seems that Basic Authorization is not available on OBS platform...
    # Only cookies OK..

    # OBS_username = os.environ['OBS_USERNAME']
    # OBS_password = os.environ['OBS_PASSWORD']
    # credential = OBS_username + ':' + OBS_password
    # b64credential = base64.b64encode(credential.encode("ascii")).decode("ascii")
    # print(b64credential)

    cookies = {
        '_obs_api_session': os.environ['OBS_COOKIE'],
    }

    headers = {
        'Accept': 'application/xml',
        'charset': 'utf-8',
        # 'Authorization': 'Basic ' + b64credential,
    }

    resp = requests.get(url, headers, cookies=cookies)
    # print(resp.text)

    soup = BeautifulSoup(resp.text, features='lxml')
    # print(soup.prettify())

    projects = []
    for project in soup.find_all('entry'):
        # print(project['name'])
        projects.append(project['name'])

    return projects


def save_to_db(projects):
    for project in projects:
        if obs_project.objects.filter(project_name=project):
            continue
        obs_project.objects.create(project_name=project)


if __name__ == '__main__':
    projects = get_projects()
    save_to_db(projects)
